package com.sptan.ssmp.service.impl;

import com.sptan.framework.redis.RedisCache;
import com.sptan.ssmp.domain.AdminUser;
import com.sptan.ssmp.dto.auth.LoginUser;
import com.sptan.ssmp.mapper.AdminUserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {

    private final AdminUserMapper adminUserMapper;

    private final RedisCache redisCache;

    @Override
    public UserDetails loadUserByUsername(String username) {
        AdminUser adminUser = (AdminUser) redisCache.getCacheObject(username);
        if (adminUser == null) {
            adminUser = adminUserMapper.selectByUserName(username);
            if (adminUser == null) {
                throw new UsernameNotFoundException("User not found");
            } else {
                return LoginUser.builder()
                    .user(adminUser)
                    .build();
            }
        } else {
            return LoginUser.builder()
                .user(adminUser)
                .build();
        }
    }

}
